package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _50二叉树中的最大路径和
 * @description
 * @date 2023/06/18 10:14
 * <p>
 * ******************************************************
 */
public class _50二叉树中的最大路径和 {

    int maxSum = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {

        dp(root);

        return maxSum;
    }

    private int dp(TreeNode node) {

        if (node == null) {
            return 0;
        }

        int left = Math.max(dp(node.left), 0);
        int right = Math.max(dp(node.right), 0);

        // 节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值
        int priceNewpath = node.val + left + right;

        // 更新答案
        maxSum = Math.max(maxSum, priceNewpath);

        // 返回节点的最大贡献值
        return node.val + Math.max(left, right);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
